package com.guass.nettyprotostuff.rpc.server;

import com.guass.nettyprotostuff.conf.ServerProperties;
import com.guass.nettyprotostuff.rpc.server.handler.ChildChannelHandler;
import com.guass.nettyprotostuff.service.RpcService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务器压测模式
 * @author guass
 */
@Slf4j
public class ServerTest {

    public void startServerTest(RpcService rpcService, ServerProperties serverProperties,
                            int sPort, int ePort){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(workerGroup, workerGroup)
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 8 * 1024 * 1024))
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, false)
                    .childOption(ChannelOption.SO_RCVBUF, 128 * 1024)
                    .childOption(ChannelOption.SO_SNDBUF, 128 * 1024)
                    .childOption(ChannelOption.SO_REUSEADDR,true)
                    .childHandler(new ChildChannelHandler(serverProperties.getRpcIdleTimeout(), rpcService));

            ChannelFuture channelFuture = serverBootstrap.bind(sPort).addListener((ChannelFutureListener)channel -> {
                log.info("guass rpc 服务启动完毕,ch={}", channel);
            });
            for (int i = 1; i <= ePort - sPort; i++) {

                int port = sPort + i;
                serverBootstrap.bind(port).addListener((ChannelFutureListener)channel -> {
                    log.info("guass rpc 服务启动完毕,ch={}, port == {}", channel,port);
                });

            }

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
